package cn.sf.sufingzuul.filterConfig;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class RuleFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取当前的请求内容
        RequestContext context=RequestContext.getCurrentContext();
        //获取当前的请求对象
        HttpServletRequest request=context.getRequest();
        //获取header中的信息
        String token=request.getHeader("token");
        //获取请求路径的url
        String url=request.getRequestURI().toString();
        //判断url中是否包含某些特定的字符,如果有特定的字符的请求可以不进行验证直接访问
        //如果不存在则需要进行验证才能通过
        if(url.indexOf("pw")!=-1){
            return "pass";
        }
        //验证是否存在token并且token的值为123456才能通过验证、
        //否则直接返回不会将请求转给对应的服务
        if(!("123456").equals(token)){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
            //设置响应对象编码格式
            context.getResponse().setContentType("text/html;charset=UTF-8");
            //设置响应对象中的信息
            context.setResponseBody("你没有权限去访问当前的路径");
            return "Access denied";
        }
        return "pass";
    }
}
